package org.sunrise.game.client.main.frame;

import org.sunrise.game.client.client.SocketClient;
import org.sunrise.game.client.client.SocketClientManager;
import org.sunrise.game.client.gen.ChatProto;
import org.sunrise.game.client.gen.TopicProto;
import org.sunrise.game.client.main.LoginManager;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MainWindow extends JFrame {
    public static MainWindow instance;
    public MainWindow() throws Exception {
        // 设置主窗口标题和大小
        setTitle("Sunrise");
        setSize(800, 600); // 调整窗口大小以适应背景图
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null); // 窗口居中
        UIManager.setLookAndFeel("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel");
        // 设置背景图片
        ImageIcon backgroundIcon = new ImageIcon(getClass().getClassLoader().getResource("background.png"));
        JLabel backgroundLabel = new JLabel(backgroundIcon);
        backgroundLabel.setLayout(new GridBagLayout()); // 使用 GridBagLayout 居中按钮

        // 初始化按钮面板
        JPanel buttonPanel = new JPanel(new GridLayout(4, 1, 10, 10));
        buttonPanel.setOpaque(false); // 设置按钮面板透明

        JButton loginButton = new JButton("登录");
        JButton chatButton = new JButton("聊天");
        JButton mapButton = new JButton("地图");
        JButton changeThemeButton = new JButton("主题");

        // 设置按钮样式
        Font buttonFont = new Font("宋体", Font.BOLD, 18);
        loginButton.setFont(buttonFont);
        chatButton.setFont(buttonFont);
        mapButton.setFont(buttonFont);
        changeThemeButton.setFont(buttonFont);

        // 登录按钮点击事件
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String uid = JOptionPane.showInputDialog(MainWindow.this, "请输入账号：", "登录", JOptionPane.PLAIN_MESSAGE);
                if (uid != null && !uid.trim().isEmpty()) {
                    SocketClient client = SocketClientManager.getInstance();
                    client.setUid(uid);
                    LoginManager.login(client);
                    JOptionPane.showMessageDialog(MainWindow.this, "登录成功！欢迎，" + uid, "提示", JOptionPane.INFORMATION_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(MainWindow.this, "账号不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 聊天室按钮点击事件
        chatButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                openChatRoom();
            }
        });

        // 地图按钮点击事件
        mapButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                openMapFrame();
            }
        });

        // 主题按钮点击事件
        changeThemeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SettingManager.changeTheme(MainWindow.this);
            }
        });

        // 添加按钮到面板
        buttonPanel.add(loginButton);
        buttonPanel.add(chatButton);
        buttonPanel.add(mapButton);
        buttonPanel.add(changeThemeButton);

        // 将按钮面板添加到背景图中心
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.anchor = GridBagConstraints.CENTER;
        backgroundLabel.add(buttonPanel, gbc);

        // 将背景图添加到窗口
        setContentPane(backgroundLabel);

        setVisible(true);

        // 初始化子窗口
        MapFrame.instance = new MapFrame();
        ChatRoom.instance = new ChatRoom();

        // 监听子窗口关闭事件
        ChatRoom.instance.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                setVisible(true); // 子窗口关闭后显示主窗口
            }
        });

        MapFrame.instance.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                setVisible(true); // 子窗口关闭后显示主窗口
            }
        });
    }

    // 打开聊天室窗口
    private void openChatRoom() {
        if (!checkLogin()) return;
        SocketClient client = SocketClientManager.getInstance();
        ChatRoom.instance.setVisible(true);
        setVisible(false); // 隐藏主窗口

        client.sendMsg(TopicProto.MBasePacketData.newBuilder()
                .setPacketType(TopicProto.TOPIC.TOPIC_TYPE_CHAT)
                .setPacketId(ChatProto.FROM_CLIENT.C2S_GetHistory_VALUE)
                .setPacketData(ChatProto.MC2S_GetHistory.newBuilder().setCount(50).build().toByteString())
                .build());
    }

    // 打开地图窗口
    private void openMapFrame() {
        if (!checkLogin()) return;
        MapFrame.instance.setVisible(true);
        setVisible(false); // 隐藏主窗口
    }

    private boolean checkLogin() {
        SocketClient client = SocketClientManager.getInstance();
        if (!client.isConnectSuccess()) {
            JOptionPane.showMessageDialog(
                    this,
                    "请先登录服务器！",
                    "未登录",
                    JOptionPane.WARNING_MESSAGE
            );
            return false;
        }
        return true;
    }
}
